package forum.communication;

import forum.server.controller.ForumFacadeInt;
import forum.server.domain.LoggedInUser;
import forum.server.exceptions.*;

/**
 * @author Tamir 
 *
 */
public class LoginMessage extends ClientMessage {

	private static final long serialVersionUID = -2723317717299435031L;
	
	/** 
	 * The username of the user. 
	 */
	private String username;
	
	/** 
	 * The password of the user. 
	 */
	private String password;

	public LoginMessage(String username, String password) {
		this.username = username;
		this.password = password; 
	}
	
	/* (non-Javadoc)
	 * @see forum.tcpcommunicationlayer.ClientMessage#doOperation(forum.server.domainlayer.ForumFacade)
	 */
	@Override
	public ServerResponse doOperation(ForumFacadeInt forum) {
		try {
			LoggedInUser tUser=forum.login(this.username, this.password);
			int permission=0;
			switch (tUser.getPermission()) {
			case ADMIN:
				permission=3;
				break;
			case MODERATOR:
				permission=2;
				break;
			case LOGGEDINUSER:
				permission=1;
				break;
			default:
				permission=0;
				break;
			}
			return new ServerResponse("Successfully logged in as: \""+this.username+"\""+" with permission "+permission ,true);
		} catch (IncorrectLoginException e) {
			return new ServerResponse(e.getMessage(),false);
		} catch (NoSuchUserException e) {
			return new ServerResponse("Username doesn't exist.",false);
		} catch (DatabaseException e) {
			return new ServerResponse("The server is currently down for maintanance.\nPlease try again later.",false);
		}
	}

}
